package com.base.controller.api;

import com.base.comm.CommContent;
import com.base.helper.*;
import com.base.po.acess.AcessToken;
import com.base.po.acess.TokenUtils;
import com.base.po.param.NetState;
import com.base.po.param.VosModelList;
import com.base.po.sqlparam.PayinfoesExamplePage;
import com.base.po.voip.*;
import com.base.po.voip.RechargeablecardsExample.Criteria;
import com.base.service.*;
import com.base.utils.GsonUtil;
import com.base.utils.IP;
import com.base.utils.Produce;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 充值控制器
 *
 * @author Administrator
 *
 */
@Controller
@RequestMapping("/recharge")
public class RechargeController extends LoginController {

	private final SubscribersService subscribersService;

	private final RechargeablecardsService rechargeablecardsService;

	private final RechargeablecardsGiftService rechargeablecardsGiftService;

	private final PayinfoesService payinfoesService;

	private final RechargeratiosService rechargeratiosService;

	private final UsersService usersService;

	private final SmsconfigsService smsconfigsService;

	private final ChangeRecordService changeRecordService;

	private final LogsService logsService;// log日志

	private final RedisCacheManager redisCacheManager;

	private final static Object lock = new Object();

	public RechargeController(SubscribersService subscribersService,
							  RechargeablecardsService rechargeablecardsService,
							  RechargeablecardsGiftService rechargeablecardsGiftService,
							  PayinfoesService payinfoesService,
							  RechargeratiosService rechargeratiosService,
							  UsersService usersService,
							  SmsconfigsService smsconfigsService,
							  ChangeRecordService changeRecordService,
							  LogsService logsService,
							  RedisCacheManager redisCacheManager) {
		this.subscribersService = subscribersService;
		this.rechargeablecardsService = rechargeablecardsService;
		this.rechargeablecardsGiftService = rechargeablecardsGiftService;
		this.payinfoesService = payinfoesService;
		this.rechargeratiosService = rechargeratiosService;
		this.usersService = usersService;
		this.smsconfigsService = smsconfigsService;
		this.changeRecordService = changeRecordService;
		this.logsService = logsService;
		this.redisCacheManager = redisCacheManager;
	}

	// 交易明细
	@CrossOrigin
	@RequestMapping(value = "/getPayInfo", method = RequestMethod.POST)
	public @ResponseBody
    NetState getPayInfo(HttpServletRequest request, Integer Page) {
		NetState netState = new NetState();
		String AuthorizationToken = request.getHeader("SDB-Authorization");
		AcessToken acessToken = TokenUtils.getAcessToken(AuthorizationToken);
		if (acessToken == null || acessToken.equals("")) {
			netState.setData("数据签名错误");
			netState.setErrorCode(NetState.SIGN_ERROR);
		} else {
			String Mobile = acessToken.getMobile();
			String AgentID = acessToken.getParentid();

			List<Subscribers> sub = subscribersService.selectBySub(Mobile,AgentID);

			// 验证参数
			if (Mobile == null || Mobile.equals("") || AgentID == null || AgentID.equals("")) {
				netState.setErrorCode(NetState.PARAMS_ERROR);
				netState.setData("客户端参数错误");
			} else {
				PayinfoesExamplePage examplePage = new PayinfoesExamplePage();
				examplePage.pagesize = 10;
				if (Page == null || Page == 0) {
					examplePage.start = 0;
				} else {
					examplePage.start = (Page - 1) * examplePage.pagesize;
				}
				examplePage.rows = examplePage.pagesize;// 设置首次分页
				examplePage.setOrderByClause("PayTime");
				examplePage.getOredCriteria()
						.add(examplePage.createCriteria().andMobileEqualTo(Mobile).andParentidEqualTo(sub.get(0).getShopid()));
				List<Payinfoes> payinfoes = payinfoesService.selectByExamplePage(examplePage);
				if (payinfoes != null) {
					netState.setErrorCode(NetState.SUCCESS_CONN);
					netState.setData("充值数据");
					netState.setJson(payinfoes);
				} else {
					netState.setErrorCode(NetState.NODATA);
					netState.setData("无数据");
				}
			}
		}
//		Apiinfoes apiinfoes = ApiinfoesHelper.createApiinfoes(request, " 交易明细");
//		apiinfoesService.insert(ApiinfoesHelper.setApiinfoes(apiinfoes,
//				AuthorizationToken + Produce.parmsToString(Page), GsonUtil.createJsonString(netState)));
		return netState;
	}

	// 购物卡充值 / 话费充值 /扫一扫充值
	@CrossOrigin
	@RequestMapping(value = "/payinfo", method = RequestMethod.POST)
	public @ResponseBody
    NetState payinfo(HttpServletRequest request, String Pwd, String Cardno, String Mobile, String ParentId)
			throws Exception {
		NetState netState = new NetState();
//		netState.setErrorCode(NetState.ERROR_OPERATE);
//		netState.setData("充值功能正在维护中");
		String AuthorizationToken = request.getHeader("SDB-Authorization");
		if (AuthorizationToken==null||AuthorizationToken.equals("")){
			netState.setErrorCode(NetState.SIGN_ERROR);
			netState.setData("token为空");
			return netState;
		}
		AcessToken acessToken = TokenUtils.getAcessToken(AuthorizationToken);


		if (redisCacheManager.hasKey("cards:"+Cardno+":pwd"+Pwd)){
			netState.setErrorCode(NetState.FEAILED);
			netState.setData("系统已在处理,请勿频繁充值");
			return netState;
		}
		if (acessToken == null && Mobile == null && ParentId == null) {
			netState.setData("数据签名错误");
			netState.setErrorCode(NetState.SIGN_ERROR);
		} else {
			String ParentID = null;
			if (acessToken != null && !acessToken.equals("")){
				//验证token是否正确
				String mobile1=acessToken.getMobile();
				String parentid1=acessToken.getParentid();
				List<String> subscribersList=subscribersService.selectByMobileAndParentId(mobile1,parentid1);
				if (subscribersList.size()>0){
					ParentID = acessToken.getParentid();
				}else{
					netState.setErrorCode(NetState.SIGN_ERROR);
					netState.setData("token错误");
					return netState;
				}

			}
			if (ParentId != null){
				ParentID = ParentId;
			}

			// 1.验证参数是否传递
			if (Mobile == null || Mobile.equals("") || ParentID == null || ParentID.equals("") || Pwd == null
					|| Pwd.equals("") || Cardno == null || Cardno.equals("")) {
				netState.setErrorCode(NetState.PARAMS_ERROR);
				netState.setData("客户端参数错误");
			} else {
				// 2.验证用户是否存在
				SubscribersExample subscribersExample = new SubscribersExample();
				subscribersExample.getOredCriteria().add(subscribersExample.createCriteria().andMobileEqualTo(Mobile)
						.andParentidEqualTo(ParentID).andDatastatusEqualTo(true));
				List<Subscribers> subscribers = subscribersService.selectByExample(subscribersExample);
				if (subscribers.size() > 0) {
					Subscribers users = subscribers.get(0);
					Integer money = 0;
					// 2.验证卡号\卡密是否正确
					if (Cardno != null && Pwd != null) {
//						RechargeablecardsExample example = new RechargeablecardsExample();
//						Criteria criteria = example.createCriteria();
//						criteria.andCardnoEqualTo(Cardno);
//						criteria.andPwdEqualTo(Pwd);
//						criteria.andStatusEqualTo(0);
//						example.getOredCriteria().add(criteria);
						int status=0;
						List<Rechargeablecards> a = rechargeablecardsService.selectByCPS(Cardno,Pwd,status);
						if (a != null && a.size() == 1) {
							// 3.验证卡密是否存在,验证卡密是否被使用
							Rechargeablecards cards = a.get(0);
							synchronized (lock){
								if (redisCacheManager.hasKey("cards:"+Cardno+":pwd"+Pwd)){
									netState.setErrorCode(NetState.FEAILED);
									netState.setData("系统已在处理,请勿频繁充值");
									return netState;
								}
								redisCacheManager.set("cards:"+cards.getCardno()+":pwd"+cards.getPwd(),"1");
								redisCacheManager.expire("cards:"+cards.getCardno()+":pwd"+cards.getPwd(),300);
							}

							// 4.验证卡密是否被冻结
							if (cards.getDatastatus()) {
								money = cards.getMoney();
								// 5. 验证该充值卡的代理商是否存在,验证卡密代理商权限（admin不能充值）
								Users cardAgents = usersService.selectByPrimaryKey(cards.getParentid());
								// TODO String appprentid = null;
								// if (cardAgents.getRole() == 1) {// 卡代理是OEM
								// appprentid = cardAgents.getId();
								// } else if (cardAgents.getRole() == 2) {//
								// 卡代理是商家
								// appprentid = cardAgents.getParentid();
								// }
								if (cardAgents != null && cardAgents.getDatastatus() == true
										&& cardAgents.getRole() != 0) {
									UsersExample usersExample = new UsersExample();
									usersExample.getOredCriteria().add(usersExample.createCriteria()
											.andDatastatusEqualTo(true).andIdEqualTo(ParentID));
									List<Users> agents = usersService.selectByExample(usersExample);
									// 5. 验证该用户的代理商是否存在
									if (agents != null && agents.size() == 1) {
										Users agent = agents.get(0);

//										List<String> allShop = usersService.selectAllShop(ParentID);
//										if(allShop.contains(cards.getParentid()) == false) {
//											netState.setErrorCode(NetState.NODATA);
//											netState.setData("充值失败,"+agent.getUsername()+"未找到充值卡信息");
//											return netState;
//										}

										//开卡距离今天几天
										int time = Produce.differentDays(cards.getCreatetime(), Produce.getNowDate());
										//距离时间大于有效期  就是过期了
										if(time>cards.getTermofvalidity()) {
											netState.setErrorCode(NetState.AMOUNT_NOT_QUERY);
											netState.setData("充值卡已过期");
											return netState;
										}

										// 查询充值者 变更前话费余额
										BigDecimal beforeB = new BigDecimal(0);
										// 备注
										String remark = null;
										try {
											// TODO 暂时配注
											String userR = VosHelper
													.GetVosAccount("{accounts:['" + agent.getAgentprefix() + users.getMobile() + "']}");
											if (userR != null) {
												VosModelList userR1 = GsonUtil.getObject(userR, VosModelList.class);
												if (userR1.retCode == 0) {
													beforeB = userR1.infoCustomers[0].getMoney();
												} else {
													beforeB = new BigDecimal(0);
													remark = "暂无记录";
												}
											}
										} catch (Exception e) {
											beforeB = new BigDecimal(0);
											remark = "暂无记录";
										}
										//查询充值者  变更前话费有效期
										Date beforeTimeB = users.getEndtime();
										// 查询充值者  变更前购物金余额
										BigDecimal beforeS = BigDecimal.valueOf(users.getShopBalance());
										// 查询充值者 变更前购物金有效期
										Date beforeTimeS = new SimpleDateFormat("yyyy-MM-dd")
												.parse(users.getShopEnddate());
										// 变更话费金额
										BigDecimal changeB = new BigDecimal(0);
										// 变更购物金额
										BigDecimal changeS = new BigDecimal(0);
										// 查询充值者 变更后话费有效期
										Date changeTimeB = new Date();
										// 查询充值者 变更后购物金有效期
										Date changeTimeS = new Date();

										// 验证卡密类型(判断输入类型是否与卡密类型一致)
										switch (cards.getType()) {
										// a.包月（800）
										case 1:
											cards.setMoney(800);
											users.setIsmonth(true);
											break;
										// b.包季度（2500）
										case 2:
											cards.setMoney(2500);
											users.setIsquarter(true);
											break;
										// c.包年（10000）
										case 3:
											cards.setMoney(10000);
											users.setIsyear(true);
											break;
										// d.第4类 电话卡
										case 4:
											break;
										// e.第5类 购物余额
										case 5:
											// 更改卡状态
											cards.setStatus(1);
											cards.setUsetime(Produce.getNowDate());
											cards.setMobile(Mobile);
											int code = rechargeablecardsService.updateByPrimaryKeySelective(cards);

											if (code != 1){
												netState.setErrorCode(NetState.ERROR_OPERATE);
												netState.setData("充值卡更新错误");
												return netState;
											}

											// 充值购物余额，设定有效期，陔余额不可打电话 只可以购物
											users.setShopBalance(users.getShopBalance() + cards.getMoney());
											// 变更的购物金额
											changeS = BigDecimal.valueOf(cards.getMoney());
											users.setShopEnddate(new SimpleDateFormat("yyyy-MM-dd").format(
													Produce.plusDay(cards.getProbationperiod(), Produce.getNowDate())));
											// 变更后的购物金有效期
											changeTimeS = Produce.plusDay(cards.getProbationperiod(), Produce.getNowDate());
											changeTimeB = beforeTimeB;
											if (cards.getIsupdateshop() == 1){
												if (agent.getIsupdateshop() == 1){
													users.setShopid(cards.getParentid());
												}
											}
											// 更新用户状态
											subscribersService.updateByPrimaryKeySelective(users);

											if (!ParentID.equals("68403bea3cae46d9b05650011ce9cab1")){
												payinfoesService.insert(Mobile, cards.getCardno(), cards.getPwd(),
														cards.getParentid(), true, cards.getMoney(), true, 1, null, null,
														null, 2);
											}else{
												payinfoesService.insert(Mobile, cards.getCardno(), cards.getPwd(),
														users.getShopid(), true, cards.getMoney(), true, 1, null, null,
														null, 2);
											}

											try {
												// 充值变更记录
												changeRecordService.insertSelective(new ChangeRecord(users.getParentid(),
														users.getShopid(), users.getId(), Produce.getNowDate(), beforeB, changeB,
														1, beforeTimeB, changeTimeB, "卡密充值", beforeS, changeS, 1, beforeTimeS,
														changeTimeS, "卡密充值", remark));
											} catch (Exception e) {
												logsService.insert(CommContent.TYPE_CREATE, Mobile + "卡密充值余额变更记录异常", agent.getUsername(), true,
														IP.getIpAddr(request));
											}

											if(cards.getType() != 8){
												// 发送短信
												SmsconfigsExample smsconfigsExample = new SmsconfigsExample();
												smsconfigsExample.getOredCriteria().add(smsconfigsExample.createCriteria()
														.andAgentidEqualTo(ParentID).andDatastatusEqualTo(true));
												List<Smsconfigs> s = smsconfigsService.selectByExample(smsconfigsExample);
												if (s != null && s.size() > 0) {
													Smsconfigs sms = s.get(0);
													if (sms.getCount() > 0) {
													    switch (agent.getSmstype()){
                                                            case 1:
                                                                String jsondata = SmsHelper.SendSms(Mobile, money, sms.getMzid(),
                                                                        sms.getSignid(), sms.getType());
                                                                WebHelper.PostData(sms.getUrl(), jsondata, sms.getContenttype(),
                                                                        null);
                                                                break;
                                                            case 3:
                                                                RYSmsHelper.sendRecharge(Mobile, agent.getUsername(), money, 2);
                                                                break;
                                                        }
													}
												}
											}
											netState.setErrorCode(NetState.SUCCESS_CONN);
											netState.setData("充值成功");
											break;
										}
										if (cards.getType() != 5) {
											cards.setStatus(1);
											cards.setUsetime(Produce.getNowDate());
											cards.setMobile(users.getMobile());
											int code5 = rechargeablecardsService.updateByPrimaryKeySelective(cards);

											if (code5 != 1){
												netState.setErrorCode(NetState.ERROR_OPERATE);
												netState.setData("充值卡更新错误");
												return netState;
											}

											String payinfo = VosHelper
													.PayVosAccount("{\"ownerName\":\"" + agent.getAgentprefix()
															+ users.getMobile() + "\",\"ownerType\":\"2\",\"money\":\""
															+ cards.getMoney() + "\",\"memo\":\"" + agent.getUsername()
															+ "充值卡(" + Pwd + "),充值" + cards.getMoney() + "元\"}");

											VosModelList v1 = GsonUtil.getObject(payinfo, VosModelList.class);
											if (v1.retCode == 0) {
												// 变更话费金额
												changeB = BigDecimal.valueOf(cards.getMoney());
												if (cards.getIsupdateshop() == 1){
													if (agent.getIsupdateshop() == 1){
														users.setShopid(cards.getParentid());
													}
												}
												// TODO
												// 本地更新用户截止日期，判断截止日期进行更新
												users.setEndtime(Produce.plusDay(cards.getProbationperiod(),
														Produce.getNowDate()));
												// 变更后话费有效期
												changeTimeB = Produce.plusDay(cards.getProbationperiod(), Produce.getNowDate());
												// 变更后购物金有效期
												changeTimeS = beforeTimeS;
												subscribersService.updateByPrimaryKeySelective(users);
												// TODO
												// VOS更新用户截止日期，判断截止日期进行更新
												String upuserinfo = VosHelper
														.ModifyVosAccount(
																"{\"account\":\"" + agent.getAgentprefix()
																		+ users.getMobile() + "\",\"feeRateGroup\":\""
																		+ cards.getFeelroute()
																		+ "\",\"agentAccount\":\""
																		+ cardAgents.getUsername()
																		+ "\",\"validTime\":\""
																		+ Produce.plusDay(cards.getProbationperiod(),
																				Produce.getNowDate()).getTime()
																		+ "\"}");

												VosModelList v2 = GsonUtil.getObject(upuserinfo, VosModelList.class);

												// 如果类型为等值卡 送话费等值的购物金
												if(cards.getType() == 6){
													cards.setStatus(1);
													cards.setUsetime(Produce.getNowDate());
													cards.setMobile(users.getMobile());
													int code6 = rechargeablecardsService.updateByPrimaryKeySelective(cards);

													if (code6 != 1){
														netState.setErrorCode(NetState.ERROR_OPERATE);
														netState.setData("充值卡更新错误");
														return netState;
													}

													// 充值购物余额，设定有效期，陔余额不可打电话 只可以购物
													users.setShopBalance(users.getShopBalance() + cards.getMoney());
													// 变更的购物金额
													changeS = BigDecimal.valueOf(cards.getMoney());
													users.setShopEnddate(new SimpleDateFormat("yyyy-MM-dd").format(
															Produce.plusDay(cards.getProbationperiod(), Produce.getNowDate())));
													// 变更后的购物金有效期
													changeTimeS = Produce.plusDay(cards.getProbationperiod(), Produce.getNowDate());
													if (cards.getIsupdateshop() == 1){
														if (agent.getIsupdateshop() == 1){
															users.setShopid(cards.getParentid());
														}
													}
													// 更新用户状态
													subscribersService.updateByPrimaryKeySelective(users);

													rechargeablecardsService.updateByPrimaryKeySelective(cards);

													if (!ParentID.equals("68403bea3cae46d9b05650011ce9cab1")){
														payinfoesService.insert(Mobile, cards.getCardno(), cards.getPwd(),
																cards.getParentid(), true, cards.getMoney(), true, 1, null, null,
																null, 3);
													}else{
														payinfoesService.insert(Mobile, cards.getCardno(), cards.getPwd(),
																users.getShopid(), true, cards.getMoney(), true, 1, null, null,
																null, 3);
													}

												}else if(cards.getType() == 7){
													cards.setStatus(1);
													cards.setUsetime(Produce.getNowDate());
													cards.setMobile(users.getMobile());
													int code7 = rechargeablecardsService.updateByPrimaryKeySelective(cards);

													if (code7!= 1){
														netState.setErrorCode(NetState.ERROR_OPERATE);
														netState.setData("充值卡更新错误");
														return netState;
													}

													RechargeablecardsGift gift = rechargeablecardsGiftService.selectByBatch(cards.getBatch());
													// 充值购物余额，设定有效期，陔余额不可打电话 只可以购物
													users.setShopBalance(users.getShopBalance() + gift.getShopmoney());
													// 变更的购物金额
													changeS = BigDecimal.valueOf(cards.getMoney());
													users.setShopEnddate(new SimpleDateFormat("yyyy-MM-dd").format(
															Produce.plusDay(cards.getProbationperiod(), Produce.getNowDate())));
													// 变更后的购物金有效期
													changeTimeS = Produce.plusDay(cards.getProbationperiod(), Produce.getNowDate());
													if (cards.getIsupdateshop() == 1){
														if (agent.getIsupdateshop() == 1){
															users.setShopid(cards.getParentid());
														}
													}
													// 更新用户状态
													subscribersService.updateByPrimaryKeySelective(users);

													rechargeablecardsService.updateByPrimaryKeySelective(cards);

													if (!ParentID.equals("68403bea3cae46d9b05650011ce9cab1")){
														payinfoesService.insert(Mobile, cards.getCardno(), cards.getPwd(),
																cards.getParentid(), true, cards.getMoney(), true, 1, null, null,
																null, 4);
													}else{
														payinfoesService.insert(Mobile, cards.getCardno(), cards.getPwd(),
																users.getShopid(), true, cards.getMoney(), true, 1, null, null,
																null, 4);
													}
												}else{
													if (!ParentID.equals("68403bea3cae46d9b05650011ce9cab1")){
														payinfoesService.insert(Mobile, cards.getCardno(), cards.getPwd(),
																cards.getParentid(), true, cards.getMoney(), true, 1, null, null, null,
																1);
													}else{
														payinfoesService.insert(Mobile, cards.getCardno(), cards.getPwd(),
																users.getShopid(), true, cards.getMoney(), true, 1, null, null, null,
																1);
													}
												}

												try {
													// 充值变更记录
													changeRecordService.insertSelective(new ChangeRecord(users.getParentid(),
															users.getShopid(), users.getId(), Produce.getNowDate(), beforeB,
															changeB, 1, beforeTimeB, changeTimeB, "卡密充值", beforeS, changeS,
															1, beforeTimeS, changeTimeS, "卡密充值", remark));
												} catch (Exception e) {
													logsService.insert(CommContent.TYPE_CREATE, Mobile + "卡密充值余额变更记录异常", agent.getUsername(), true,
															IP.getIpAddr(request));
												}

												// 推送充值信息
												try{
													if (agent.getIsrechargepush() == 1){
//														List<JpushId> jpushId = jpushIdService.selectByUserID(users.getId());
//														if (jpushId != null && jpushId.size() > 0){
//															JPushUtil.setPush("成功充值话费" + changeB + "元,购物金" + changeS + "元", jpushId.get(0).getRegistrationid(), agent);
//														}
													}
												}catch (Exception e){
													System.out.println("推送异常");
												}

												if (cards.getType() != 8){
													// 发送短信
													SmsconfigsExample smsconfigsExample = new SmsconfigsExample();
													smsconfigsExample.getOredCriteria()
															.add(smsconfigsExample.createCriteria()
																	.andAgentidEqualTo(ParentID)
																	.andDatastatusEqualTo(true));
													List<Smsconfigs> s = smsconfigsService
															.selectByExample(smsconfigsExample);
													if (s != null && s.size() > 0) {
														Smsconfigs sms = s.get(0);
														if (sms.getCount() > 0) {
														    switch (agent.getSmstype()){
                                                                case 1:
                                                                    String jsondata = null;
                                                                    if (cards.getType() != 4) {
                                                                        jsondata = SmsHelper.SendSms(Mobile, Mobile,
                                                                                sms.getTcid(), sms.getSignid(), sms.getType());
                                                                    } else {
                                                                        jsondata = SmsHelper.SendSms(Mobile, money,
                                                                                sms.getMzid(), sms.getSignid(), sms.getType());
                                                                    }
                                                                    WebHelper.PostData(sms.getUrl(), jsondata,
                                                                            sms.getContenttype(), null);
                                                                    break;
                                                                case 3:
                                                                    RYSmsHelper.sendRecharge(Mobile, agent.getUsername(), money, 2);
                                                                    break;
                                                            }
														}
													}
												}
												netState.setErrorCode(NetState.SUCCESS_CONN);
												netState.setData("充值成功");
											} else {
												netState.setErrorCode(NetState.SYSTEM_ERROR);
												netState.setData("充值失败，您的账户可能出现了问题,请联系客服");
											}
										}
									} else {
										netState.setErrorCode(NetState.ACCOUNT_ERROR);
										netState.setData("充值失败，您的代理商未查到");
									}
								} else {
									netState.setErrorCode(NetState.API_NOT_PER);
									netState.setData("充值失败，您的卡存在权限异常");
								}
							} else {
								netState.setErrorCode(NetState.NODATA);
								netState.setData("充值失败，您的卡密已经过期");
							}
						} else {
							netState.setErrorCode(NetState.PARAMS_ERROR);
							netState.setData("您输入的充值卡有误或已被充值，请检查充值卡号以及密码");
						}
					} else {
						netState.setErrorCode(NetState.PARAMS_ERROR);
						netState.setData("您输入的充值卡有误，请检查充值卡号以及密码");
					}
				} else {
					try{
						netState = this.register(request, Mobile, ParentID, Mobile, null, null, null, null, null, null);
						if (netState.getErrorCode() == 2000){
							this.payinfo(request, Pwd, Cardno, Mobile, ParentID);
						}else{
							netState.setErrorCode(NetState.PARAMS_ERROR);
							netState.setData("请检查该用户是否真实存在,或是否被冻结");
						}
					}catch (Exception e){
						netState.setErrorCode(NetState.PARAMS_ERROR);
						netState.setData("请检查该用户是否真实存在,充值异常");
					}
				}
			}
		}
//		Apiinfoes apiinfoes = ApiinfoesHelper.createApiinfoes(request, "购物卡充值 / 话费充值 /扫一扫充值");
//		apiinfoesService.insert(ApiinfoesHelper.setApiinfoes(apiinfoes, AuthorizationToken + Produce.parmsToString(Pwd),
//				GsonUtil.createJsonString(netState)));
		return netState;
	}

	// 微信端 购物卡充值 / 话费充值 /扫一扫充值
	@RequestMapping(value = "/wxPayInfo", method = RequestMethod.POST)
	public @ResponseBody
    NetState wxPayInfo(HttpServletRequest request, HttpServletResponse response,
                       String Pwd, String Cardno, String Mobile)throws Exception {
		//微信端 跨域请求
		response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with,content-type,Authorization");
		NetState netState = new NetState();
		String AuthorizationToken = request.getHeader("Authorization");
		AcessToken acessToken = TokenUtils.getAcessToken(AuthorizationToken);
		if (acessToken == null || acessToken.equals("")) {
			netState.setData("数据签名错误");
			netState.setErrorCode(NetState.SIGN_ERROR);
		} else {
			String ParentID = acessToken.getParentid();
			// 1.验证参数是否传递
			if (Mobile == null || Mobile.equals("") || ParentID == null || ParentID.equals("") || Pwd == null
					|| Pwd.equals("") || Cardno == null || Cardno.equals("")) {
				netState.setErrorCode(NetState.PARAMS_ERROR);
				netState.setData("客户端参数错误");
			} else {
				// 2.验证用户是否存在
				SubscribersExample subscribersExample = new SubscribersExample();
				subscribersExample.getOredCriteria().add(subscribersExample.createCriteria().andMobileEqualTo(Mobile)
						.andParentidEqualTo(ParentID).andDatastatusEqualTo(true));
				List<Subscribers> subscribers = subscribersService.selectByExample(subscribersExample);
				if (subscribers.size() > 0) {
					Subscribers users = subscribers.get(0);
					Integer money = 0;
					// 2.验证卡号\卡密是否正确
					if (Cardno != null && Pwd != null) {
						RechargeablecardsExample example = new RechargeablecardsExample();
						Criteria criteria = example.createCriteria();
						criteria.andCardnoEqualTo(Cardno);
						criteria.andPwdEqualTo(Pwd);
						criteria.andStatusEqualTo(0);
						example.getOredCriteria().add(criteria);
						List<Rechargeablecards> a = rechargeablecardsService.selectByExample(example);
						if (a != null && a.size() == 1) {
							// 3.验证卡密是否存在,验证卡密是否被使用
							Rechargeablecards cards = a.get(0);
							// 4.验证卡密是否被冻结
							if (cards.getDatastatus()) {
								money = cards.getMoney();
								// 5. 验证该充值卡的代理商是否存在,验证卡密代理商权限（admin不能充值）
								Users cardAgents = usersService.selectByPrimaryKey(cards.getParentid());
								// TODO String appprentid = null;
								// if (cardAgents.getRole() == 1) {// 卡代理是OEM
								// appprentid = cardAgents.getId();
								// } else if (cardAgents.getRole() == 2) {//
								// 卡代理是商家
								// appprentid = cardAgents.getParentid();
								// }
								if (cardAgents != null && cardAgents.getDatastatus() == true
										&& cardAgents.getRole() != 0) {
									UsersExample usersExample = new UsersExample();
									usersExample.getOredCriteria().add(usersExample.createCriteria()
											.andDatastatusEqualTo(true).andIdEqualTo(ParentID));
									List<Users> agents = usersService.selectByExample(usersExample);
									// 5. 验证该用户的代理商是否存在
									if (agents != null && agents.size() == 1) {
										Users agent = agents.get(0);
										// 验证卡密类型(判断输入类型是否与卡密类型一致)
										switch (cards.getType()) {
										// a.包月（800）
										case 1:
											cards.setMoney(800);
											users.setIsmonth(true);
											break;
										// b.包季度（2500）
										case 2:
											cards.setMoney(2500);
											users.setIsquarter(true);
											break;
										// c.包年（10000）
										case 3:
											cards.setMoney(10000);
											users.setIsyear(true);
											break;
										// d.第4类 电话卡
										case 4:
											break;
										// e.第5类 购物余额
										case 5:
											// 充值购物余额，设定有效期，陔余额不可打电话 只可以购物
											users.setShopBalance(users.getShopBalance() + cards.getMoney());
											users.setShopEnddate(new SimpleDateFormat("yyyy-MM-dd").format(
													Produce.plusDay(cards.getProbationperiod(), Produce.getNowDate())));
											if (cards.getIsupdateshop() == 1){
												if (agent.getIsupdateshop() == 1){
													users.setShopid(cards.getParentid());
												}
											}
											// 更新用户状态
											subscribersService.updateByPrimaryKeySelective(users);
											// 更改卡状态
											cards.setStatus(1);
											cards.setUsetime(Produce.getNowDate());
											cards.setMobile(Mobile);
											rechargeablecardsService.updateByPrimaryKeySelective(cards);
											payinfoesService.insert(Mobile, cards.getCardno(), cards.getPwd(),
													cards.getParentid(), true, cards.getMoney(), true, 1, null, null,
													null, 2);

											if (cards.getType() != 8){
												// 发送短信
												SmsconfigsExample smsconfigsExample = new SmsconfigsExample();
												smsconfigsExample.getOredCriteria().add(smsconfigsExample.createCriteria()
														.andAgentidEqualTo(ParentID).andDatastatusEqualTo(true));
												List<Smsconfigs> s = smsconfigsService.selectByExample(smsconfigsExample);
												if (s != null && s.size() > 0) {
													Smsconfigs sms = s.get(0);
													if (sms.getCount() > 0) {
														String jsondata = SmsHelper.SendSms(Mobile, money, sms.getMzid(),
																sms.getSignid(), sms.getType());
														WebHelper.PostData(sms.getUrl(), jsondata, sms.getContenttype(),
																null);
													}
												}
											}

											netState.setErrorCode(NetState.SUCCESS_CONN);
											netState.setData("充值成功");
											break;
										}
										if (cards.getType() != 5) {
											String payinfo = VosHelper
													.PayVosAccount("{\"ownerName\":\"" + agent.getAgentprefix()
															+ users.getMobile() + "\",\"ownerType\":\"2\",\"money\":\""
															+ cards.getMoney() + "\",\"memo\":\"" + agent.getUsername()
															+ "充值卡(" + Pwd + "),充值" + cards.getMoney() + "元\"}");

											VosModelList v1 = GsonUtil.getObject(payinfo, VosModelList.class);
											if (v1.retCode == 0) {
												if (cards.getIsupdateshop() == 1){
													if (agent.getIsupdateshop() == 1){
														users.setShopid(cards.getParentid());
													}
												}
												// TODO
												// 本地更新用户截止日期，判断截止日期进行更新
												users.setEndtime(Produce.plusDay(cards.getProbationperiod(),
														Produce.getNowDate()));
												subscribersService.updateByPrimaryKeySelective(users);
												cards.setStatus(1);
												cards.setUsetime(Produce.getNowDate());
												cards.setMobile(users.getMobile());
												rechargeablecardsService.updateByPrimaryKeySelective(cards);
												// TODO
												// VOS更新用户截止日期，判断截止日期进行更新
												String upuserinfo = VosHelper
														.ModifyVosAccount(
																"{\"account\":\"" + agent.getAgentprefix()
																		+ users.getMobile() + "\",\"feeRateGroup\":\""
																		+ cards.getFeelroute()
																		+ "\",\"agentAccount\":\""
																		+ cardAgents.getUsername()
																		+ "\",\"validTime\":\""
																		+ Produce.plusDay(cards.getProbationperiod(),
																				Produce.getNowDate()).getTime()
																		+ "\"}");

												VosModelList v2 = GsonUtil.getObject(upuserinfo, VosModelList.class);

												// 如果类型为等值卡 送话费等值的购物金
												if(cards.getType() == 6){
													// 充值购物余额，设定有效期，陔余额不可打电话 只可以购物
													users.setShopBalance(users.getShopBalance() + cards.getMoney());
													users.setShopEnddate(new SimpleDateFormat("yyyy-MM-dd").format(
															Produce.plusDay(cards.getProbationperiod(), Produce.getNowDate())));
													if (cards.getIsupdateshop() == 1){
														if (agent.getIsupdateshop() == 1){
															users.setShopid(cards.getParentid());
														}
													}
													// 更新用户状态
													subscribersService.updateByPrimaryKeySelective(users);
													// 更改卡状态
													cards.setStatus(1);
													cards.setUsetime(Produce.getNowDate());
													cards.setMobile(Mobile);
													rechargeablecardsService.updateByPrimaryKeySelective(cards);
													payinfoesService.insert(Mobile, cards.getCardno(), cards.getPwd(),
															cards.getParentid(), true, cards.getMoney(), true, 1, null, null,
															null, 3);
												}else{
													payinfoesService.insert(Mobile, cards.getCardno(), cards.getPwd(),
															cards.getParentid(), true, cards.getMoney(), true, 1, null, null, null,
															1);
												}

												if (cards.getType() != 8){
													// 发送短信
													SmsconfigsExample smsconfigsExample = new SmsconfigsExample();
													smsconfigsExample.getOredCriteria()
															.add(smsconfigsExample.createCriteria()
																	.andAgentidEqualTo(ParentID)
																	.andDatastatusEqualTo(true));
													List<Smsconfigs> s = smsconfigsService
															.selectByExample(smsconfigsExample);
													if (s != null && s.size() > 0) {
														Smsconfigs sms = s.get(0);
														if (sms.getCount() > 0) {
															String jsondata = null;
															if (cards.getType() != 4) {
																jsondata = SmsHelper.SendSms(Mobile, Mobile,
																		sms.getTcid(), sms.getSignid(), sms.getType());
															} else {
																jsondata = SmsHelper.SendSms(Mobile, money,
																		sms.getMzid(), sms.getSignid(), sms.getType());
															}
															WebHelper.PostData(sms.getUrl(), jsondata,
																	sms.getContenttype(), null);
														}
													}
												}
												netState.setErrorCode(NetState.SUCCESS_CONN);
												netState.setData("充值成功");
											} else {
												netState.setErrorCode(NetState.SYSTEM_ERROR);
												netState.setData("充值失败，您的账户可能出现了问题,请联系客服");
											}
										}
									} else {
										netState.setErrorCode(NetState.ACCOUNT_ERROR);
										netState.setData("充值失败，您的代理商未查到");
									}
								} else {
									netState.setErrorCode(NetState.API_NOT_PER);
									netState.setData("充值失败，您的卡存在权限异常");
								}
							} else {
								netState.setErrorCode(NetState.NODATA);
								netState.setData("充值失败，您的卡密已经过期");
							}
						} else {
							netState.setErrorCode(NetState.PARAMS_ERROR);
							netState.setData("您输入的充值卡有误或已被充值，请检查充值卡号以及密码");
						}
					} else {
						netState.setErrorCode(NetState.PARAMS_ERROR);
						netState.setData("您输入的充值卡有误，请检查充值卡号以及密码");
					}
				} else {
					netState.setErrorCode(NetState.PARAMS_ERROR);
					netState.setData("请检查该用户是否真实存在,或是否被冻结");
				}
			}
		}
//		Apiinfoes apiinfoes = ApiinfoesHelper.createApiinfoes(request, "购物卡充值 / 话费充值 /扫一扫充值");
//		apiinfoesService.insert(ApiinfoesHelper.setApiinfoes(apiinfoes, AuthorizationToken + Produce.parmsToString(Pwd),
//				GsonUtil.createJsonString(netState)));
		return netState;
	}

	// 获取在线充值信息
	@CrossOrigin
	@RequestMapping(value = "/getPayOnline", method = RequestMethod.POST)
	public @ResponseBody
    NetState getPayOnline(HttpServletRequest request, String mobile, String parentid) {
		NetState netState = new NetState();
		String AuthorizationToken = TokenUtils.getToken(parentid,mobile);
		AcessToken acessToken = TokenUtils.getAcessToken(AuthorizationToken);
		if (acessToken == null || acessToken.equals("")) {
			netState.setData("数据签名错误");
			netState.setErrorCode(NetState.SIGN_ERROR);
		} else {
			String AgentID = acessToken.getParentid();
			if (AgentID == null || AgentID.equals("")) {
				netState.setErrorCode(NetState.PARAMS_ERROR);
				netState.setData("参数异常");
			} else {
				List<Subscribers> subscribersList = subscribersService.selectBySub(mobile, parentid);
				if(subscribersList != null && subscribersList.size() > 0){
					AgentID = subscribersList.get(0).getShopid();
					RechargeratiosExample rechargeratiosExample = new RechargeratiosExample();
					rechargeratiosExample.setOrderByClause("Grade");
					rechargeratiosExample.getOredCriteria().add(
							rechargeratiosExample.createCriteria().andAgentidEqualTo(AgentID).andDatastatusEqualTo(true));
					List<Rechargeratios> rechargeratios = rechargeratiosService.selectByExample(rechargeratiosExample);
					if (rechargeratios != null) {
						netState.setErrorCode(NetState.SUCCESS_CONN);
						netState.setData("获取到在线充值数据");
						netState.setJson(rechargeratios);
						netState.setOtherJson(usersService.selectByPrimaryKey(AgentID).getIsalipay());
					} else {
						netState.setErrorCode(NetState.NODATA);
						netState.setData("暂无数据");
					}
				}else {
					netState.setErrorCode(NetState.NODATA);
					netState.setData("未查询到用户信息");
				}
			}
		}
//		Apiinfoes apiinfoes = ApiinfoesHelper.createApiinfoes(request, "获取在线充值信息");
//		apiinfoesService.insert(
//				ApiinfoesHelper.setApiinfoes(apiinfoes, AuthorizationToken, GsonUtil.createJsonString(netState)));
		return netState;
	}

	// 支付宝参数(通用)
	@RequestMapping(value = "/aliPram", method = RequestMethod.POST)
	public @ResponseBody
    NetState aliPram(HttpServletRequest request, String ID, String Mobile, BigDecimal RegiMoney,
                     Integer Role) {
		NetState netState = new NetState();
		if (ID == null || ID.equals("")) {
			netState.setErrorCode(NetState.PARAMS_ERROR);
			netState.setData("参数异常");
		} else {
			UsersExample usersExample = new UsersExample();
			usersExample.getOredCriteria().add(usersExample.createCriteria().andIdEqualTo(ID).andDatastatusEqualTo(true)
					.andAppidIsNotNull().andAppidNotEqualTo("").andKeypathIsNotNull().andKeypathNotEqualTo(""));
			List<Users> user = usersService.selectByExample(usersExample);
			if (user != null && user.size() > 0) {
				netState.setErrorCode(NetState.SUCCESS_CONN);
				netState.setData("支付成功");
			} else {
				netState.setErrorCode(NetState.ACCOUNT_ERROR);
				netState.setData("支付失败，该代理商不存在或者未配置支付信息");
			}
		}
//		Apiinfoes apiinfoes = ApiinfoesHelper.createApiinfoes(request, "获取在线充值信息");
//		apiinfoesService.insert(ApiinfoesHelper.setApiinfoes(apiinfoes,
//				Produce.parmsToString(ID, Mobile, RegiMoney, Role), GsonUtil.createJsonString(netState)));
		return netState;
	}

	// 支付失败时调用的接口
	@RequestMapping(value = "/cancelPay", method = RequestMethod.POST)
	public @ResponseBody
    NetState concelPay(HttpServletRequest request, String OrderNum) {
		NetState netState = new NetState();
		PayinfoesExample payinfoesExample = new PayinfoesExample();
		payinfoesExample.getOredCriteria().add(payinfoesExample.createCriteria().andOrdernumEqualTo(OrderNum)
				.andDatastatusEqualTo(true).andTypeEqualTo(3));
		List<Payinfoes> payinfoes = payinfoesService.selectByExample(payinfoesExample);
		if (payinfoes != null && payinfoes.size() > 0) {
			Payinfoes record = payinfoes.get(0);
			record.setAlistatus("2");
			payinfoesService.updateByPrimaryKeySelective(record);
			netState.setErrorCode(NetState.SUCCESS_CONN);
			netState.setData("订单已经关闭支付");
		} else {
			netState.setErrorCode(NetState.NODATA);
			netState.setData("该订单不存在");
		}
//		Apiinfoes apiinfoes = ApiinfoesHelper.createApiinfoes(request, "支付失败");
//		apiinfoesService.insert(ApiinfoesHelper.setApiinfoes(apiinfoes, Produce.parmsToString(OrderNum),
//				GsonUtil.createJsonString(netState)));
		return netState;
	}

}
